﻿using System.Linq.Expressions;
using MudBlazor;
using SageKing.OpenIddict.Services.BaseService;

namespace SageKing.Blazor.OpenIdService.Components.Shared;

public partial class TableSet
{

    #region 参数

    public override AuthComponentTabTableBase<TemplateConfigBase, long> Me { get => this; }

    /// <summary>
    /// 表列名
    /// </summary>
    [Parameter]
    public Dictionary<string, TemplateConfigBase> TableColumnsNames { get; set; }

    /// <summary>
    /// 动态显示的列名
    /// </summary>
    public override List<string> ColumnsByNamesShow { get; set; } = ["OrderNo", "KKey", "VValue", "SourceType", "Code", "Enable", "SortNo", "CreateUserName", "Description", TemplateKeyConsts.JsonDicColumn];

    public override Dictionary<string, string> ColumnsTitleDic { get; set; } = new() {
        { "SortNo", "序号" },
        { "OrderNo", "排序" },
        { "KKey", "列名" },
        { "VValue", "值" },
        { "Code", "编码" },
        { "Enable", "是否可用" },
        { "SourceType", "来源类型" },
        { "Description", "描述" },
        { "CreateUserName", "时间相关" },
    };
    #endregion

    #region Inject 相关 
    [Inject]
    public TemplateBaseService<TemplateConfigBase, long> _dataService { get; set; }
    public override IBaseService<TemplateConfigBase, long> DataService => _dataService;

    [Inject]
    public SysConfigResourceService sysConfig { get; set; }
    #endregion

    #region init system
    protected override async Task OnInitializedAsync()
    {
        try
        {
            TabTitle = "应用管理-表格设置";

            Editing = true;

            pageargs.PageSize = PageSize = 100;
            PageSizeOptions = [50, 100, 500, 1000];

            await base.OnInitializedAsync();
            ScrollY = "200px"; 

            await Refresh(false);

            await sysConfig.InitAuthorizationToken();

            //var data = await sysConfig.GetAsync(0);
            var dataPage = await sysConfig.GetPageAsync(new PageBaseInput() { Page = 1, PageSize = 100 });
        }
        catch (Exception ex)
        {
            Error?.ProcessError(ex);
        }

    }


    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        try
        {
            await base.OnAfterRenderAsync(firstRender);

           
        }
        catch (Exception ex)
        {
            Error?.ProcessError(ex);
        }
    }

    #endregion

    #region 查询条件相关
    #region OnSearch 

    private bool isInit = true;
    public override async Task OnSearch(PaginationEventArgs args)
    {
        tableLoading = true;

        pageargs.Page = args.Page;
        pageargs.PageSize = args.PageSize;


        List<(bool, Expression<Func<TemplateConfigBase, bool>>)> tmpWhereIf = new() {
                (searchModel.KKey.IsNotNullOrWhiteSpace(),a=> a.KKey== searchModel.KKey),
            };

        var page = new PageBaseInput() { Page = pageargs.Page, PageSize = pageargs.PageSize };

        var tmpPageData = await _dataService.GetPage(page, tmpWhereIf,
            a => a.Id, false);


        var colLst = tmpPageData.Items.Where(a => TableColumnsNames.ContainsKey(a.KKey)).ToList();

        if (colLst.Count <= 0)
        {
            colLst.AddRange(TableColumnsNames.Values.ToList());
        }
        else
        {
            //获取差异
            var diff = TableColumnsNames.Keys.Except(colLst.Select(args => args.KKey)).ToList();
            var getTmpColLst = TableColumnsNames.Values.Where(a => diff.Contains(a.KKey)).ToList();
            colLst.AddRange(getTmpColLst);
        }

        var toSortLst = colLst.Where(a => a.OrderNo <= 0).ToList();
        int sort = colLst.Max(a => a.OrderNo.GetValueOrDefault()) + 1;
        foreach (var col in toSortLst)
        {
            col.OrderNo = sort;
            sort++;
        }

        //更新
        tmpPageData.Items = colLst.OrderBy(a => a.OrderNo);

        CheckPageData(tmpPageData);

        pageData = tmpPageData;

        tableLoading = false;
        await Task.CompletedTask;
    }

    public override void CheckPageData(PageBase<TemplateConfigBase> pageData)
    {
        //检测 扩展列
        foreach (var item in pageData.Items)
        {
            if (item.JsonDicColumn.IsNullOrEmpty())
            {
                item.JsonDicColumnDic = JsonColumnDic.toJsonStr().JsonTo<Dictionary<string, JsonColumnPropertiesBase>>();
            }

            item.JsonDicColumnDic ??= new Dictionary<string, JsonColumnPropertiesBase>();

            foreach (var itemjson in item.JsonDicColumnDic)
            {
                var key = itemjson.Key;
                if (itemjson.Value.Value == null)
                {
                    if (JsonColumnDic.TryGetValue(key, out var getDefault))
                    {
                        itemjson.Value.Value = getDefault?.DefaultValue.ConvertTo(getDefault.Type.GetTypeByName());
                    }
                }

                if (!JsonColumnDic.ContainsKey(key))
                {
                    item.JsonDicColumnDic.Remove(key);
                }
            }

            foreach (var key in JsonColumnDic)
            {
                if (!item.JsonDicColumnDic.ContainsKey(key.Key))
                {
                    item.JsonDicColumnDic[key.Key] = key.Value;
                }
            }
        }
    }
    #endregion
    #endregion

    #region Table DefinitionColumns
    /// <summary>
    /// 动态列定义处理
    /// </summary>
    /// <param name="propertyName"></param>
    /// <param name="column"></param>
    /// <returns></returns>

    public override void DefinitionColumns(string propertyName, IFieldColumn column)
    {
        try
        {

            var getColDefine = DefinitionColumnsBase(propertyName, column);

            //to do



        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
    #endregion


}
